package com.atguigu.gulimall.product.utils;

import com.atguigu.common.utils.CommonResponse;
import com.atguigu.gulimall.product.exception.GuliProductRuntimeException;
import com.atguigu.gulimall.product.exception.enums.ExceptionErrorCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

@SuppressWarnings("rawtypes")
@Component
public class ResponseUtil {
    private static MessageSource source;

    @Autowired
    public void setSource(MessageSource messageSource) {
        source = messageSource;
    }

    public static CommonResponse success() {
        return build(null);
    }

    public static <T> CommonResponse success(T data) {
        CommonResponse<T> build = build(data);
        build.setCode("0");
        return build;
    }

    public static <T> CommonResponse<T> build(T data) {
        CommonResponse<T> commonResponse = new CommonResponse<>();
        commonResponse.setData(data);
        return commonResponse;
    }

    public static CommonResponse fail(final String errorCode, final String errorMessage) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setCode(errorCode);
        commonResponse.setMsg(errorMessage);
        commonResponse.setSuccess(false);
        return commonResponse;
    }

    public static CommonResponse fail(final GuliProductRuntimeException exception) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setCode(exception.getErrorCode());
        String message = source.getMessage(exception.getErrorKey(), null, LocaleContextHolder.getLocale());
        commonResponse.setMsg(message);
        commonResponse.setSuccess(false);
        return commonResponse;
    }

    public static CommonResponse fail(final ExceptionErrorCodeEnum errorCodeEnum) {
        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setCode(errorCodeEnum.getErrorCode());
        String message = source.getMessage(errorCodeEnum.getErrorKey(), null, LocaleContextHolder.getLocale());
        commonResponse.setMsg(message);
        commonResponse.setSuccess(false);
        return commonResponse;
    }

}
